/**
 *
 */
package com.mtons.mblog.web.controller.site.comment;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.mtons.mblog.base.lang.Consts;
import com.mtons.mblog.base.lang.Result;
import com.mtons.mblog.modules.rabbitmq.PostMqMessage;
import com.mtons.mblog.modules.rabbitmq.RabbitConstant;
import com.mtons.mblog.modules.service.CommentService;
import com.mtons.mblog.modules.vo.AccountProfile;
import com.mtons.mblog.modules.vo.CommentVO;
import com.mtons.mblog.web.controller.BaseController;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.util.HtmlUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * @author langhsu
 */
@RestController
@RequestMapping("/comment")
@ConditionalOnProperty(name = "site.controls.comment", havingValue = "true", matchIfMissing = true)
public class CommentController extends BaseController {
    @Autowired
    private CommentService commentService;
    @Autowired
    private ApplicationContext applicationContext;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @RequestMapping("/list/{toId}")
    public IPage<CommentVO> view(HttpServletRequest request, @PathVariable Long toId) {
//        int pageNo = ServletRequestUtils.getIntParameter(request, "pageNo", 0);
//        int pageSize = ServletRequestUtils.getIntParameter(request, "pageSize", Consts.PAGE_DEFAULT_SIZE);
        return commentService.paging4PostId(getPage(request), toId);
    }

    @RequestMapping("/submit")
    public Result post(Long toId, String text, HttpServletRequest request) {
        if (!isAuthenticated()) {
            return Result.failure("请先登录在进行操作");
        }

        long pid = ServletRequestUtils.getLongParameter(request, "pid", 0);

        if (toId <= 0 || StringUtils.isBlank(text)) {
            return Result.failure("操作失败");
        }

        try {
            AccountProfile profile = getProfile();

            CommentVO c = new CommentVO();
            c.setPostId(toId);
            c.setContent(HtmlUtils.htmlEscape(text));
            c.setAuthorId(profile.getId());

            c.setPid(pid);

            commentService.post(c);

            sendMessage(profile.getId(), toId, pid);
        } catch (Exception e) {
            return Result.failure(e.getMessage());
        }

        return Result.successMessage("发表成功");
    }

    @RequestMapping("/delete")
    public Result delete(@RequestParam(name = "id") Long id) {
        Result data;
        try {
            commentService.delete(id, getProfile().getId());
            data = Result.success();
        } catch (Exception e) {
            data = Result.failure(e.getMessage());
        }
        return data;
    }

    /**
     * 发送通知
     *
     * @param userId
     * @param postId
     */
    private void sendMessage(long userId, long postId, long pid) {
//        MessageEvent event = new MessageEvent("MessageEvent");
//        event.setFromUserId(userId);

        if (pid > 0) {
//            event.setEvent(Consts.MESSAGE_EVENT_COMMENT_REPLY);
//            event.setCommentParentId(pid);
            // 此处不知道文章作者, 让通知事件系统补全
            rabbitTemplate.convertAndSend(RabbitConstant.POST_EXCHAGE, RabbitConstant.POST_ROUTING_KEY,
                    new PostMqMessage(userId, Consts.MESSAGE_EVENT_COMMENT_REPLY, postId, pid));
        } else {
            rabbitTemplate.convertAndSend(RabbitConstant.POST_EXCHAGE, RabbitConstant.POST_ROUTING_KEY,
                    new PostMqMessage(userId, Consts.MESSAGE_EVENT_COMMENT, postId));
//            event.setEvent(Consts.MESSAGE_EVENT_COMMENT);
        }

//        event.setPostId(postId);
//        applicationContext.publishEvent(event);
    }
}